package com.android.car_bluetooth_audio;

import static com.android.car_bluetooth_audio.ble.service.BleProfileService.BROADCAST_CONNECTION_STATE;
import static com.android.car_bluetooth_audio.ble.service.BleProfileService.BROADCAST_ERROR;
import static com.android.car_bluetooth_audio.ble.service.BleProfileService.BROADCAST_SERVICES_DISCOVERED;
import static com.android.car_bluetooth_audio.ble.service.BleProfileService.EXTRA_CONNECTION_STATE;
import static com.android.car_bluetooth_audio.ble.service.BleProfileService.EXTRA_DEVICE;
import static com.android.car_bluetooth_audio.ble.service.VibrationBleProfileService.ACTION_DISCONNECT;
import static com.android.car_bluetooth_audio.ble.service.VibrationBleProfileService.BROADCAST_DEVICE_ON;
import static com.android.car_bluetooth_audio.ble.service.VibrationBleProfileService.BROADCAST_EQ_DATA;
import static com.android.car_bluetooth_audio.ble.service.VibrationBleProfileService.BROADCAST_READ_DATA;
import static com.android.car_bluetooth_audio.ble.service.VibrationBleProfileService.BROADCAST_RESET_0OR180_DATA;
import static com.android.car_bluetooth_audio.ble.service.VibrationBleProfileService.BROADCAST_RESET_DATA;
import static com.android.car_bluetooth_audio.ble.service.VibrationBleProfileService.BROADCAST_SAVE_DATA;
import static com.android.car_bluetooth_audio.ble.service.VibrationBleProfileService.BROADCAST_SWITCH_DATA;
import static com.android.car_bluetooth_audio.ble.service.VibrationBleProfileService.BROADCAST_SYSC_DATA;
import static com.android.car_bluetooth_audio.ble.service.VibrationBleProfileService.EXTRA_TEMPERATURE;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;


import com.android.car_bluetooth_audio.ble.ParserUtils;
import com.android.car_bluetooth_audio.ble.VibrationBleManager;
import com.android.car_bluetooth_audio.ble.scanner.ScannerFragment;
import com.android.car_bluetooth_audio.ble.service.BleProfileService;
import com.android.car_bluetooth_audio.ble.service.VibrationBleProfileService;
import com.android.car_bluetooth_audio.widget.ProgressBarView;
import com.android.car_bluetooth_audio.widget.VoiceChannelView;

import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import no.nordicsemi.android.support.v18.scanner.BluetoothLeScannerCompat;
import no.nordicsemi.android.support.v18.scanner.ScanCallback;
import no.nordicsemi.android.support.v18.scanner.ScanResult;
import no.nordicsemi.android.support.v18.scanner.ScanSettings;


public class MainActivity extends AppCompatActivity implements ScannerFragment.OnDeviceSelectedListener {
    private RelativeLayout rl_open;
    private ImageView iv_open;
    private RelativeLayout rl_bluetooth;
    private ImageView iv_bluetooth;
    private TextView tv_popular;
    private TextView tv_rock;
    private TextView tv_e5;
    private TextView tv_custom;
    private VoiceChannelView voice1;
    private VoiceChannelView voice2;
    private VoiceChannelView voice3;
    private VoiceChannelView voice4;
    private VoiceChannelView voice5;
    private VoiceChannelView voice6;
    private VoiceChannelView voice7;
    private ProgressBarView boost_progress;
    private ProgressBarView volumn_progress;
    private TextView tv_save;
    private TextView tv_reset;
    private VibrationBleProfileService.VibrationBinder mService;
    //蓝牙信息
    private BluetoothDevice mBluetoothDevice;
    private String mDeviceName;
    private TextView tv_num0;
    private TextView tv_num180;
    private int isChoose;
    private TextView tv1;
    private TextView tv2;
    private TextView tv3;
    private TextView tv4;
    private TextView tv5;
    private TextView tv6;
    private TextView tv7;
    Timer timer;
    private boolean isOpenList;
    boolean isClickBonded;
    private final BroadcastReceiver mBroadcastConnectReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            Log.e("actions是多少",action);
            switch (action){
                case  BluetoothAdapter.ACTION_STATE_CHANGED:
                    int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                    Log.e("蓝牙状态怎样", String.valueOf(blueState));
                    switch (blueState){
                        case BluetoothAdapter.STATE_ON:
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Log.e("等5s","是的欧尼");
                                    blueToothConnectStatus1();
                                }
                            },1000);

//                            Toast.makeText(context,"蓝牙已经打开",Toast.LENGTH_SHORT).show();
                            break;
                    }
                    break;
            }
        }
    };

    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            switch (action){
                  // 监视蓝牙关闭和打开的状态
//                case  BluetoothAdapter.ACTION_STATE_CHANGED:
//                    int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
//                    Log.e("蓝牙状态怎样", String.valueOf(blueState));
//                    switch (blueState){
//                        case BluetoothAdapter.STATE_ON:
//                            Toast.makeText(context,"蓝牙已经打开",Toast.LENGTH_SHORT).show();
//                            break;
//                    }
//                    break;
                case BROADCAST_SERVICES_DISCOVERED:
//                    setLoading(false,"连接蓝牙成功:");
                    Log.e("鏈接藍牙成功","成功");
                    BluetoothLeScannerCompat scanner1 = BluetoothLeScannerCompat.getScanner();
                    Log.e("停止扫描","是都");
                    scanner1.stopScan(scanCallback);
//                    boolean primary = intent.getBooleanExtra(EXTRA_SERVICE_PRIMARY,false);
                    BluetoothDevice device = intent.getParcelableExtra(EXTRA_DEVICE);
                    SharedPreferences sharedPreferences = getSharedPreferences("eq",Context.MODE_PRIVATE);
                    sharedPreferences.edit().putString("bluetooth_device_address",device.getAddress())
                            .putString("bluetooth_device_name",device.getName())
                            .apply();

//                    String address = sharedPreferences.getString("bluetooth_device_address","");
                    if (mService!=null){

                        byte bytes[] = {0x01,0x03};
                        Log.e("数组内容是", Arrays.toString(bytes));
                        mService.syncData(bytes);
                    }
                    iv_bluetooth.setImageResource(R.mipmap.bluetooth_on);

                    break;
                case BROADCAST_ERROR:
//                    setLoading(false,"连接错误");
                    Toast.makeText(MainActivity.this,"蓝牙连接失败",Toast.LENGTH_SHORT).show();
                    iv_bluetooth.setImageResource(R.mipmap.bluetooth_off);
                    iv_open.setImageResource(R.mipmap.switch_off1);
                    setStyleDefaultColor();
                    break;
                case BROADCAST_CONNECTION_STATE:
                    Log.e("蓝牙突刺","土豆丝");//EXTRA_CONNECTION_STATE
                    int state = intent.getIntExtra(EXTRA_CONNECTION_STATE,0);
                    Log.e("连接状态", String.valueOf(state));
                    if (state<=0){
                        iv_bluetooth.setImageResource(R.mipmap.bluetooth_off);
                        iv_open.setImageResource(R.mipmap.switch_off1);
                        setStyleDefaultColor();
                        Log.e("连接状态兰哟喂", String.valueOf(isClickBonded));
//                        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
                        if (isClickBonded){
                            SharedPreferences sharedPreferences1 = getSharedPreferences("eq",Context.MODE_PRIVATE);
                            sharedPreferences1.edit().remove("bluetooth_device_name").remove("bluetooth_device_address").apply();
//                            isClickBonded=false;
                            return;
                        }
                        BluetoothLeScannerCompat scanner = BluetoothLeScannerCompat.getScanner();
                        ScanSettings settings = new ScanSettings.Builder()
                                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                                .setReportDelay(2000)
                                .setUseHardwareBatchingIfSupported(false).build();
                        try {
                            Log.e("开始扫描","是都");
                            scanner.startScan(null, settings, scanCallback);
                        }catch (Exception e){
                            e.printStackTrace();
                        }


//                        sharedPreferences1.edit().putString("bluetooth_device_address","")
//                                .putString("bluetooth_device_name","")
//                                .apply();
//                        if (timer!=null){
//                            timer.cancel();
//                            timer.purge();
//                            timer = new Timer();
//                            timer.schedule(new TimerTask() {
//                                @Override
//                                public void run() {
//                                    Log.e("进入这哦","好的");
//
//                                    Log.e("设备地址", "地址:" + deviceAddress);
//                                    if (!TextUtils.isEmpty(deviceAddress)) {
//                                        BluetoothDevice bluetoothDevice = adapter.getRemoteDevice(deviceAddress);
//                                        Log.e("获取蓝牙设置", String.valueOf(bluetoothDevice==null));
//                                        if (bluetoothDevice!=null){
//                                            adapter.sc
//                                            Log.e("设备信息",bluetoothDevice.getName()+"/"+bluetoothDevice.getType()+"/"+bluetoothDevice.getAlias()+"/"+bluetoothDevice.getBondState());
//                                        }
////                                        Intent service = new Intent(MainActivity.this, VibrationBleProfileService.class);
////                                        service.putExtra(BleProfileService.EXTRA_DEVICE_ADDRESS, deviceAddress);
////                                        service.putExtra(BleProfileService.EXTRA_DEVICE_NAME, name);
////                                        startService(service);
////                                        bindService(service, mServiceConnection, 0);
//                                    }
//                                }
//                            },0,2000);
//                        }
                    }
                    break;
            }
        }
    };

    private final BroadcastReceiver mDataReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            switch (action) {
                case BROADCAST_SYSC_DATA:
                    String[] value = intent.getStringArrayExtra(EXTRA_TEMPERATURE);
                    Log.e("字符串长度", String.valueOf(value.length));

                    for (int i =0;i<value.length;i++){
                        String s = value[i];
                        Log.e("s是多少",s);
                        if (i == 0){//开关
                            String i1 = s.substring(2);
                            if (i1.equals("00")){
                                iv_open.setImageResource(R.mipmap.switch_off1);
                            }else {
                                iv_open.setImageResource(R.mipmap.switch_on1);
                            }
                        }else if (i==1){//音量
                            String maxVolum = s.substring(6,8);
                            String currentVolum = s.substring(4,6);
                            int max = Integer.parseInt(maxVolum,16);
                            int current = Integer.parseInt(currentVolum,16);
                            Log.e("current","是多少"+current);
                            Log.e("max", String.valueOf(max));
                            volumn_progress.setMax(max);
                            volumn_progress.setProgress(Float.valueOf((current+"")));
                        }else if (i==2){

                        }else if (i==3){//0 180

                            //重置信息
                            reset0Or180(s);

                        }else if (i==4){

                        }else if (i==5){

                        }else if (i==6){
                            Log.e("开始获取数据",s);
                            setEqValue(s);
                        }


                    }
                    break;
                case BROADCAST_SWITCH_DATA:
                    String i1  = intent.getStringExtra(EXTRA_TEMPERATURE);
                    String s = i1.substring(2);
                    if (s.equals("00")){
                        iv_open.setImageResource(R.mipmap.switch_off1);
                    }else {
                        iv_open.setImageResource(R.mipmap.switch_on1);
                    }
                    break;
                case BROADCAST_EQ_DATA:
                    String eq  = intent.getStringExtra(EXTRA_TEMPERATURE);
                    setEqValue(eq);
                    break;
                case BROADCAST_RESET_DATA:
                    String resetData  = intent.getStringExtra(EXTRA_TEMPERATURE);
                    setEqValue(resetData);
                    break;
                case BROADCAST_SAVE_DATA:
//                    String Data  = intent.getStringExtra(EXTRA_TEMPERATURE);
                    setSaveEqValue();
                    break;
                case BROADCAST_RESET_0OR180_DATA:
                    Log.e("0是的","嗖嗖的");
                    String msg  = intent.getStringExtra(EXTRA_TEMPERATURE);
                    reset0Or180(msg);
                    break;
                case BROADCAST_DEVICE_ON:
                    Log.e("到","手动");
                    break;
            }
        }
    };

    private void reset0Or180(String msg) {
        String i3 = msg.substring(4);
        Log.e("s搜索多少",i3);
        if (i3.equals("00")){
            isChoose=0;
            tv_num180.setBackground(null);
            tv_num0.setBackgroundResource(R.drawable.shape_r5_white);
        }else {
            isChoose=180;
            tv_num0.setBackground(null);
            tv_num180.setBackgroundResource(R.drawable.shape_r5_white);
        }
    }

    protected void setBarColor() {

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) { // 5.0 以上全透明状态栏
            //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏 加下面几句可以去除透明状态栏的灰色阴影,实现纯透明
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
//            if(txtBlack){//黑色字
            getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//                if(color<0){
//                    getWindow().setStatusBarColor(Color.WHITE);
//                }else{
//                    getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
//            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//                    getWindow().setStatusBarColor(getResources().getColor(color));
            getWindow().setStatusBarColor(Color.parseColor("#a0aeb7"));
//                }

//            }
//            else{//白色字
//                6.0 以上可以设置状态栏的字体为黑色.使用下面注释的这行打开亮色状态栏模式,实现黑色字体,白底的需求用这句setStatusBarColor(Color.WHITE);
//                 getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//                getWindow().setStatusBarColor(getResources().getColor(color));
//            }else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){//4.4 全透明状态栏
            // getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            }

        }
    }

    private void setSaveEqValue(){

        tv_custom.setTextColor(Color.parseColor("#1afa29"));
        tv_popular.setTextColor(Color.parseColor("#9b615f"));
        tv_e5.setTextColor(Color.parseColor("#9b615f"));
        tv_rock.setTextColor(Color.parseColor("#9b615f"));

    }

        private void setEqValue(String eq) {
//            0a07060101040b0807010108
            Log.e("eq是多少",eq);
            String e1 = eq.substring(4,6);
            String e2 = eq.substring(6,8);
            String e3 = eq.substring(8,10);
            String e4 = eq.substring(10,12);
            String e5 = eq.substring(12,14);
            String e6 = eq.substring(14,16);
            String e7 = eq.substring(16,18);
            String e8 = eq.substring(18,20);
            String e9 = eq.substring(20,22);
            String e10 = eq.substring(22,24);

            int e1_1 = Integer.parseInt(e1,16);
            int n1 = e1_1-7;
            tv1.setText(String.valueOf(n1));
            int pos1= (int) (16-e1_1-0.5);
            Log.e("pos1", String.valueOf(pos1));
            voice1.setDefaultPositionNoListener(pos1);

            int e2_1 = Integer.parseInt(e2,16);
            int n2 = e2_1-7;
            tv2.setText(String.valueOf(n2));
            int pos2= (int) (16-e2_1-0.5);
            Log.e("pos2", String.valueOf(pos2));
            voice2.setDefaultPositionNoListener(pos2);

            int e3_1 = Integer.parseInt(e3,16);
            int pos3= (int) (16-e3_1-0.5);
            int n3 = e3_1-7;
            tv3.setText(String.valueOf(n3));
            Log.e("pos3", String.valueOf(pos3));
            voice3.setDefaultPositionNoListener(pos3);

            int e4_1 = Integer.parseInt(e4,16);
            boost_progress.setProgress(Float.valueOf((e4_1+"")));

            int e5_1 = Integer.parseInt(e5,16);
            int pos5= (int) (16-e5_1-0.5);
            int n4 = e5_1-7;
            tv4.setText(String.valueOf(n4));
            Log.e("pos5", String.valueOf(pos5));
            voice4.setDefaultPositionNoListener(pos5);

            int e6_1 = Integer.parseInt(e6,16);
            int pos6= (int) (16-e6_1-0.5);
            int n5 = e6_1-7;
            tv5.setText(String.valueOf(n5));
//            Log.e("e6_1", String.valueOf(e6_1));
//            Log.e("n5", String.valueOf(n5));
//            Log.e("pos6", String.valueOf(pos6));
            voice5.setDefaultPositionNoListener(pos6);

            int e8_1 = Integer.parseInt(e8,16);
            int n6 = e8_1-7;
//            Log.e("e8_1", String.valueOf(e8_1));
//            Log.e("n6", String.valueOf(n6));
            tv6.setText(String.valueOf(n6));
            int pos8= (int) (16-e8_1-0.5);
            Log.e("pos8", String.valueOf(pos8));
            voice6.setDefaultPositionNoListener(pos8);

            int e9_1 = Integer.parseInt(e9,16);
            int pos9= (int) (16-e9_1-0.5);
            int n7 = e9_1-7;
            tv7.setText(String.valueOf(n7));
            Log.e("pos9", String.valueOf(pos9));
            voice7.setDefaultPositionNoListener(pos9);
        }


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            setBarColor();
            initView();
            initBroadcast();
            initListener();
            blueToothConnectStatus();

        }

        public void initView(){
            timer = new Timer();
            rl_open = findViewById(R.id.rl_open);
            iv_open = findViewById(R.id.iv_open);
            rl_bluetooth = findViewById(R.id.rl_bluetooth);
            iv_bluetooth = findViewById(R.id.iv_bluetooth);
            tv_popular = findViewById(R.id.tv_popular);
            tv_rock = findViewById(R.id.tv_rock);
            tv_e5 = findViewById(R.id.tv_e5);
            tv_custom = findViewById(R.id.tv_custom);
            voice1 = findViewById(R.id.voice1);
            voice2 = findViewById(R.id.voice2);
            voice3 = findViewById(R.id.voice3);
            voice4 = findViewById(R.id.voice4);
            voice5 = findViewById(R.id.voice5);
            voice6 = findViewById(R.id.voice6);
            voice7 = findViewById(R.id.voice7);
            tv_reset = findViewById(R.id.tv_reset);
            tv_save = findViewById(R.id.tv_save);
            tv_num0 = findViewById(R.id.tv_num0);
            tv1 = findViewById(R.id.tv1);
            tv2 = findViewById(R.id.tv2);
            tv3 = findViewById(R.id.tv3);
            tv4 = findViewById(R.id.tv4);
            tv5 = findViewById(R.id.tv5);
            tv6 = findViewById(R.id.tv6);
            tv7 = findViewById(R.id.tv7);
            tv_num180 = findViewById(R.id.tv_num180);
            boost_progress = findViewById(R.id.boost_progress);
            volumn_progress = findViewById(R.id.volumn_progress);
            setStyleDefaultColor();

        }

    private void setStyleDefaultColor() {
        tv_custom.setTextColor(Color.parseColor("#9b615f"));
        tv_popular.setTextColor(Color.parseColor("#9b615f"));
        tv_e5.setTextColor(Color.parseColor("#9b615f"));
        tv_rock.setTextColor(Color.parseColor("#9b615f"));
    }

    private void initBroadcast() {

            LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, makeIntentFilter());
            LocalBroadcastManager.getInstance(this).registerReceiver(mDataReceiver, makeIntentFilter1());
        }

        private IntentFilter makeIntentFilter() {
            final IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(BROADCAST_SERVICES_DISCOVERED);
            intentFilter.addAction(BROADCAST_CONNECTION_STATE);
            intentFilter.addAction(BROADCAST_ERROR);
            // 监视蓝牙关闭和打开的状态
            intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
            return intentFilter;

        }

    private IntentFilter makeIntentFilter2() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        return intentFilter;

    }

        private IntentFilter makeIntentFilter1() {
            final IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(BROADCAST_SYSC_DATA);
            intentFilter.addAction(BROADCAST_SWITCH_DATA);
            intentFilter.addAction(BROADCAST_EQ_DATA);
            intentFilter.addAction(BROADCAST_READ_DATA);
            intentFilter.addAction(BROADCAST_RESET_0OR180_DATA);
            intentFilter.addAction(BROADCAST_DEVICE_ON);
            intentFilter.addAction(BROADCAST_RESET_DATA);
            intentFilter.addAction(BROADCAST_SAVE_DATA);
            return intentFilter;

        }

        //蓝牙连接状态
        private void blueToothConnectStatus() {

            SharedPreferences sharedPreferences = getSharedPreferences("eq", Context.MODE_PRIVATE);
            String deviceAddress = sharedPreferences.getString("bluetooth_device_address", "");
            String name = sharedPreferences.getString("bluetooth_device_name", "");
            Log.e("设备名字"+name, "设备地址:" + deviceAddress);
            if (!TextUtils.isEmpty(deviceAddress)) {
                if (isBleEnabled()) {
                    isClickBonded=false;
//                setLoading(true,"正在连接蓝牙...");
                    Intent service = new Intent(this, VibrationBleProfileService.class);
                    service.putExtra(BleProfileService.EXTRA_DEVICE_ADDRESS, deviceAddress);
                    service.putExtra(BleProfileService.EXTRA_DEVICE_NAME, name);
                    startService(service);
                    bindService(service, mServiceConnection, 0);
//                    ScannerFragment dialog = ScannerFragment.getInstance(getFilterUUID());
//                    dialog.show(MainActivity.this.getSupportFragmentManager(), "scan_fragment");
                }
            } else {
                LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) &&
                        !manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                    askLocationSettings();
                } else {
                    ScannerFragment dialog = ScannerFragment.getInstance(getFilterUUID());
                    dialog.show(MainActivity.this.getSupportFragmentManager(), "scan_fragment");
                }

            }
        }


    private void blueToothConnectStatus1() {

        SharedPreferences sharedPreferences = getSharedPreferences("eq", Context.MODE_PRIVATE);
        String deviceAddress = sharedPreferences.getString("bluetooth_device_address", "");
        String name = sharedPreferences.getString("bluetooth_device_name", "");
        Log.e("设备名字"+name, "设备地址:" + deviceAddress);
        if (!TextUtils.isEmpty(deviceAddress)) {
            if (isBleEnabled()) {
                isClickBonded=false;
//                setLoading(true,"正在连接蓝牙...");
//                    Intent service = new Intent(this, VibrationBleProfileService.class);
//                    service.putExtra(BleProfileService.EXTRA_DEVICE_ADDRESS, deviceAddress);
//                    service.putExtra(BleProfileService.EXTRA_DEVICE_NAME, name);
//                    startService(service);
//                    bindService(service, mServiceConnection, 0);
                ScannerFragment dialog = ScannerFragment.getInstance(getFilterUUID());
                dialog.show(MainActivity.this.getSupportFragmentManager(), "scan_fragment");
            }
        } else {
            LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) &&
                    !manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                askLocationSettings();
            } else {
                ScannerFragment dialog = ScannerFragment.getInstance(getFilterUUID());
                dialog.show(MainActivity.this.getSupportFragmentManager(), "scan_fragment");
            }

        }
    }
        private void initListener() {

            tv_num0.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (isChoose != 0){
                        if (mService != null) {
//                    byte[] bytes = new byte[8];
                            byte bytes[] = {0x0a,0x03,0x00};
                            mService.send0Or180(bytes, 0);
                            isChoose=0;
                            tv_num180.setBackground(null);
                            tv_num0.setBackgroundResource(R.drawable.shape_r5_white);
                        }
                    }
                }
            });

            tv_num180.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    if (isChoose != 180){
                        if (mService != null) {
//                    byte[] bytes = new byte[8];
                            byte bytes[] = {0x0a,0x03,0x0e};
                            mService.send0Or180(bytes, 0);
                            isChoose=180;
                            tv_num0.setBackground(null);
                            tv_num180.setBackgroundResource(R.drawable.shape_r5_white);
                        }
                    }
                }
            });

            rl_open.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (mService != null) {
//                    byte[] bytes = new byte[8];
                        byte bytes[] = {0x01,0x01};
                        mService.sendSwitch(bytes, 0);
                    }


                }
            });

            tv_popular.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mService!=null){
                        byte bytes[] = {0x0b,0x01};
                        mService.sendEQMode(bytes);
                        setStyleDefaultColor();
                        tv_popular.setTextColor(Color.parseColor("#1afa29"));
                    }

                }
            });

            tv_rock.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    if (mService!=null){
                        byte bytes[] = {0x0b,0x02};
                        mService.sendEQMode(bytes);
                        setStyleDefaultColor();
                        tv_rock.setTextColor(Color.parseColor("#1afa29"));
                    }
                }
            });

            tv_e5.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    if (mService!=null){
                        byte bytes[] = {0x0b,0x03};
                        mService.sendEQMode(bytes);
                        setStyleDefaultColor();
                        tv_e5.setTextColor(Color.parseColor("#1afa29"));
                    }
                }
            });

            tv_custom.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    if (mService!=null){
                        byte bytes[] = {0x0b,0x04};
                        mService.sendEQMode(bytes);
                        setStyleDefaultColor();
                        tv_custom.setTextColor(Color.parseColor("#1afa29"));
                    }
                }
            });

            tv_save.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mService!=null){
                        byte bytes[] = {0x0a,0x08};
                        mService.sendSave(bytes);
                    }
                }
            });

            tv_reset.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mService!=null){
                        byte bytes[] = {0x0b,0x00};
                        mService.sendRest(bytes);
                    }
                }
            });

            rl_bluetooth.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ScannerFragment dialog = ScannerFragment.getInstance(getFilterUUID());
                    if (mBluetoothDevice!=null){
                        dialog.setmBluetoothDevice(mBluetoothDevice);
                    }
                    dialog.show(MainActivity.this.getSupportFragmentManager(), "scan_fragment");
                }
            });

            boost_progress.setChangeCallbackListener(new ProgressBarView.OnChangeCallbackListener() {
                @Override
                public void onChangeListener(float value,float max) {
                    Log.e("bvalue", String.valueOf(value));
                    Log.e("bmax的值", String.valueOf(max));
                    if (mService!=null){
                        int v = (int) value;
                        int m = (int) max;
                        String v1 = Integer.toHexString(v);
                        String volum;
                        if (v<=15){
                            volum = "0a05030"+v1;//04031120
                        }else {
                            volum = "0a0503"+v1;//04031120
                        }
                        Log.e("volum",volum);
                        byte bytes[] = ParserUtils.hexStringToBytes(volum);
                        String b = Arrays.toString(bytes);
                        Log.e("数组b",b);
                        mService.sendBoost(bytes);
                    }
                }
            });



            volumn_progress.setChangeCallbackListener(new ProgressBarView.OnChangeCallbackListener() {
                @Override
                public void onChangeListener(float value,float max) {

                    if (mService!=null){
                        int v = (int) value;
                        int m = (int) max;

                        String v1 = Integer.toHexString(v);
                        String m1 = Integer.toHexString(m);

                        String volum;
                        if (v<=15){
                            volum = "04030"+v1;//04031120
                        }else {
                            volum = "0403"+v1;//04031120
                        }

                        Log.e("volum",volum);
                        byte bytes[] = ParserUtils.hexStringToBytes(volum);
                        String b = Arrays.toString(bytes);

                        mService.sendVolum(bytes);



                    }
                }
            });

            voice1.setChangeCallbackListener(new VoiceChannelView.OnChangeCallbackListener() {
                @Override
                public void onChangeListener(int position) {
                    huadongtiaoSend(position,tv1);


                }

                @Override
                public void moveListener(int position) {
//                    sendMoveData(position);
                    huadongtiaoSend(position,tv1);
                }
            });

            voice2.setChangeCallbackListener(new VoiceChannelView.OnChangeCallbackListener() {
                @Override
                public void onChangeListener(int position) {
//                    huadongtiaoSend(position,tv2);

                    int realP = (int) (position-0.5);

                    if (realP>14){
                        realP = 14;
                    }
                    int finalRealP = realP;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv2.setText((0-(finalRealP -7))+"");
                        }
                    });

                    realP = 0-(realP-7)+7;
                    String v1 = Integer.toHexString(realP);
                    String data;
                    if (realP <=15){
                        data = "0a05010"+v1;
                    }else{
                        data = "0a0501"+v1;
                    }
                    sendSlideData(data);
                }

                @Override
                public void moveListener(int position) {
//                    sendMoveData(position);
                    huadongtiaoSend(position,tv2);
                }
            });

            voice3.setChangeCallbackListener(new VoiceChannelView.OnChangeCallbackListener() {
                @Override
                public void onChangeListener(int position) {
//                    huadongtiaoSend(position,tv3);

                    int realP = (int) (position-0.5);

                    if (realP>14){
                        realP = 14;
                    }
                    int finalRealP = realP;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv3.setText((0-(finalRealP -7))+"");
                        }
                    });
//                    tv3.setText((0-(realP-7))+"");
                    realP = 0-(realP-7)+7;
                    String v1 = Integer.toHexString(realP);
                    String data;
                    if (realP <=15){
                        data = "0a05020"+v1;
                    }else{
                        data = "0a0502"+v1;
                    }
                    sendSlideData(data);
                }

                @Override
                public void moveListener(int position) {
//                    sendMoveData(position);
                    huadongtiaoSend(position,tv3);
                }
            });

            voice4.setChangeCallbackListener(new VoiceChannelView.OnChangeCallbackListener() {
                @Override
                public void onChangeListener(int position) {
//                    huadongtiaoSend(position,tv4);
                    Log.e("位置地方", String.valueOf(position));
                    int realP = (int) (position-0.5);
                    Log.e("realP", String.valueOf(realP));
                    if (realP>14){
                        realP = 14;
                    }
                    int finalRealP = realP;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv4.setText((0-(finalRealP -7))+"");
                        }
                    });
//                    tv4.setText((0-(realP-7))+"");
                    realP = 0-(realP-7)+7;
                    Log.e("realP", String.valueOf(realP));
                    String v1 = Integer.toHexString(realP);
                    String data;
                    if (realP <=15){
                        data = "0a05040"+v1;
                    }else{
                        data = "0a0504"+v1;
                    }
                    sendSlideData(data);
                }

                @Override
                public void moveListener(int position) {
//                    sendMoveData(position);
                    huadongtiaoSend(position,tv4);
                }
            });

            voice5.setChangeCallbackListener(new VoiceChannelView.OnChangeCallbackListener() {
                @Override
                public void onChangeListener(int position) {
//                    huadongtiaoSend(position,tv5);

                    int realP = (int) (position-0.5);

                    if (realP>14){
                        realP = 14;
                    }
                    int finalRealP = realP;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv5.setText((0-(finalRealP -7))+"");
                        }
                    });
//                    tv5.setText((0-(realP-7))+"");
                    realP = 0-(realP-7)+7;
                    String v1 = Integer.toHexString(realP);
                    String data;
                    if (realP <=15){
                        data = "0a05050"+v1;
                    }else{
                        data = "0a0505"+v1;
                    }
                    sendSlideData(data);
                }

                @Override
                public void moveListener(int position) {
//                    sendMoveData(position);
                    huadongtiaoSend(position,tv5);
                }
            });

            voice6.setChangeCallbackListener(new VoiceChannelView.OnChangeCallbackListener() {
                @Override
                public void onChangeListener(int position) {
//                    huadongtiaoSend(position,tv6);

                    int realP = (int) (position-0.5);

                    if (realP>14){
                        realP = 14;
                    }
                    int finalRealP = realP;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv6.setText((0-(finalRealP -7))+"");
                        }
                    });
//                    tv6.setText((0-(realP-7))+"");
                    realP = 0-(realP-7)+7;
                    String v1 = Integer.toHexString(realP);
                    String data;
                    if (realP <=15){
                        data = "0a05070"+v1;
                    }else{
                        data = "0a0507"+v1;
                    }
                    sendSlideData(data);
                }

                @Override
                public void moveListener(int position) {
//                    sendMoveData(position);
                    huadongtiaoSend(position,tv6);
                }
            });

            voice7.setChangeCallbackListener(new VoiceChannelView.OnChangeCallbackListener() {
                @Override
                public void onChangeListener(int position) {
//                    huadongtiaoSend(position,tv7);

                    int realP = (int) (position-0.5);

                    if (realP>14){
                        realP = 14;
                    }
                    int finalRealP = realP;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv7.setText((0-(finalRealP -7))+"");
                        }
                    });
//                    tv7.setText((0-(realP-7))+"");
                    realP = 0-(realP-7)+7;
                    String v1 = Integer.toHexString(realP);
                    String data;
                    if (realP <=15){
                        data = "0a05080"+v1;
                    }else{
                        data = "0a0508"+v1;
                    }
                    sendSlideData(data);
                }

                @Override
                public void moveListener(int position) {
//                    sendMoveData(position);
                    huadongtiaoSend(position,tv7);
                }
            });



        }

    private void sendMoveData(int position) {

        int realP = (int) (position -0.5);

        Log.e("realP", String.valueOf(realP));
        if (realP>14){
            realP = 14;
        }
        realP = 0-(realP-7)+7;
        String v1 = Integer.toHexString(realP);
        String data;
        if (realP <=9){
            data = "0a05000"+v1;
        }else{
            data = "0a0500"+v1;
        }
        sendSlideData(data);
    }

    private void huadongtiaoSend(int position,TextView textView) {

        int realP = (int) (position -0.5);

        Log.e("realP", String.valueOf(realP));
        if (realP>14){
            realP = 14;
        }
        int n = realP-7;
        Log.e("real", String.valueOf(n));
        int finalRealP = realP;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                textView.setText((0-(finalRealP -7))+"");
            }
        });

        realP = 0-(realP-7)+7;
        String v1 = Integer.toHexString(realP);
        String data;
        if (realP <=15){
            data = "0a05000"+v1;
        }else{
            data = "0a0500"+v1;
        }
        sendSlideData(data);
    }

    public void sendSlideData(String data){

            if (mService!=null){
                byte bytes[] = ParserUtils.hexStringToBytes(data);
                mService.sendSlideData(bytes);
            }


        }


        private ServiceConnection mServiceConnection = new ServiceConnection() {

            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                mService = (VibrationBleProfileService.VibrationBinder) iBinder;
                if (timer!=null){
                    timer.cancel();//E5:DC:0C:6A:42:40
                    timer.purge();
                }
                mBluetoothDevice = mService.getBluetoothDevice();
                Log.e("bluedevice", String.valueOf("设备装在"+mBluetoothDevice==null));
// And notify user if device is connected
                if (mService.isConnected()) {
//                onDeviceConnected(mBluetoothDevice);
                } else {
                    // If the device is not connected it means that either it is still connecting,
                    // or the link was lost and service is trying to connect to it (autoConnect=true).
//                onDeviceConnecting(mBluetoothDevice);
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                Log.e("服务退出啦", "tuicchu");
                mService = null;
                mDeviceName = null;
                mBluetoothDevice = null;
                registerReceiver(mBroadcastConnectReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
//
            }
        };

        public VibrationBleProfileService.VibrationBinder getService() {
            return mService;
        }

        public UUID getFilterUUID() {
            String id = UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e").toString();
            Log.e("圣诞节哦服务", id);
            return VibrationBleManager.SERVICE_UUID;
        }

        //询问打开网络设置
        private void askLocationSettings() {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("开启位置服务");
            builder.setMessage("本应用需要开启位置服务，是否去设置界面开启位置服务？");
            builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    Intent intent = new Intent(
                            android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    MainActivity.this.startActivity(intent);
                }
            });
            builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
//                Toast.makeText(MainActivity.this, "No location provider to use",
//                        Toast.LENGTH_SHORT).show();
                }
            });
            builder.show();
        }

        /**
         * 蓝牙开关检测
         */
        public static boolean isBleEnabled() {
            final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
            return adapter != null && adapter.isEnabled();
        }

        //已选择的设备
        @Override
        public void onDeviceSelected(BluetoothDevice device, String name) {

            Intent broadcast = new Intent(ACTION_DISCONNECT);
            LocalBroadcastManager.getInstance(MainActivity.this).sendBroadcast(broadcast);
            isClickBonded = true;
//            Intent service = new Intent(this, VibrationBleProfileService.class);
//            service.putExtra(BleProfileService.EXTRA_DEVICE_ADDRESS, device.getAddress());
//            service.putExtra(BleProfileService.EXTRA_DEVICE_NAME, name);
//            startService(service);
//            bindService(service, mServiceConnection, 0);
        }

        //对话框删除
        @Override
        public void onDialogCanceled() {

        }

        //设备绑定
        @Override
        public void onDeviceBond(BluetoothDevice device, String name) {
            isClickBonded = false;
//            onDeviceSelected(device,name);
            Intent service = new Intent(this, VibrationBleProfileService.class);
            Log.e("地址",device.getAddress());//E5:DC:0C:6A:42:40
            Log.e("名字",name);
            service.putExtra(BleProfileService.EXTRA_DEVICE_ADDRESS, device.getAddress());
            service.putExtra(BleProfileService.EXTRA_DEVICE_NAME, name);
            startService(service);
            bindService(service, mServiceConnection, 0);

        }

    private ScanCallback scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(final int callbackType, final ScanResult result) {
            // do nothing
        }

        @Override
        public void onBatchScanResults(final List<ScanResult> results) {
            Log.e("扫描的结果怎样s4d",results.toString());

            if (results.size()>0){
                SharedPreferences sharedPreferences1 = getSharedPreferences("eq",Context.MODE_PRIVATE);
                String deviceAddress = sharedPreferences1.getString("bluetooth_device_address", "");
                String name = sharedPreferences1.getString("bluetooth_device_name", "");
                for (final ScanResult result : results) {
                    String address = result.getDevice().getAddress();
                    if (address.equalsIgnoreCase(deviceAddress)){
                        Intent service = new Intent(MainActivity.this, VibrationBleProfileService.class);
                        service.putExtra(BleProfileService.EXTRA_DEVICE_ADDRESS, address);
                        service.putExtra(BleProfileService.EXTRA_DEVICE_NAME, name);
                        startService(service);
                        bindService(service, mServiceConnection, 0);
                        break;
                    }
                }
            }


        }

        @Override
        public void onScanFailed(final int errorCode) {
            // should never be called
        }
    };


    }